<template>
  <div class="changeAvatar">
    <el-button type="success" @click="dialogVisible2 = true"
      >点击上传头像</el-button
    >
    <el-dialog title="上传头像" :visible.sync="dialogVisible2" width="30%">
      <el-form :model="form">
        <el-form-item :label-width="formLabelWidth" ref="uploadElement">
          <el-upload
            ref="upload"
            action="none"
           :auto-upload="false"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            list-type="picture-card"
            :limit="limitNum"
            :on-exceed="handleExceed"
            :before-upload="handleBeforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="imgChange"
            :class="{ hide: hideUpload }"
          >
            <!-- 
            action	必选参数，上传的地址	string
            on-preview 点击文件列表中已上传的文件时的钩子 function(file)
            on-remove文件列表移除文件时的钩子  function(file, fileList)
            on-change 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用	function(file, fileList)
            before-upload传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise
            且被 reject，则停止上传。  function(file)
            auto-upload 是否在选取文件后立即进行上传 boolean
            limit 最大允许上传个数 number
            on-exceed	文件超出个数限制时的钩子 function(files, fileList)
            accept	接受上传的文件类型（thumbnail-mode 模式下此参数无效） 
            list-type	文件列表的类型 text/picture/picture-card
             -->
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="uploadFile"
            >立即上传</el-button
          >
          <el-button size="small" @click="tocancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import { Message, MessageBox } from "element-ui";
export default {
  data() {
    return {
      hideUpload: false,
      dialogImageUrl: "",
      dialogVisible: false, //图片预览弹窗
      formLabelWidth: "80px",
      limitNum: 1,
      form: {},
      dialogVisible2: false, //弹窗
    };
  },
  methods: {
    // 上传文件之前的钩子
    handleBeforeUpload(file) {
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
      }
      let size = file.size / 1024 / 1024 / 2;
      if (size > 2) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
      }
      let fd = new FormData(); //通过form数据格式来传
      fd.append("picFile", file); //传文件
      console.log(fd.get("picFile"));
      axios({
        url: "/v1/users/updateicon",
        method: "post",
        data: fd,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "头像上传成功",
              type: "success",
            });
            location.reload();
          } else {
            MessageBox("头像上传失败", "提示", {
              confirmButtonText: "确定",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {},
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitNum;
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //点击上传
    uploadFile() {
      this.$refs.upload.submit();
    },
    //文件状态改变时的钩子
    imgChange(files, fileList) {
      this.hideUpload = fileList.length >= this.limitNum;
      if (fileList) {
        this.$refs.uploadElement.clearValidate();
      }
    },
    //取消上传
    tocancel() {
      this.dialogVisible2 = false;
    },
  },
};
</script>

<style lang="scss" >
.changeAvatar .hide .el-upload--picture-card {
  display: none;
}
.changeAvatar {
  margin: 0 auto;
  text-align: center;
  margin-top: 50px;
}
</style>